/**
 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
#include "uart_server.h"
#include "log_server.h"
#include "i2c_server.h"
#include "srt_server.h"
#include "memory/memory.h"
#include "common/common.h"
#include "common/base_type.h"
#include "ctrl.h"
#include "screen.h"
#include "ad.h"
#include "pico/stdlib.h"
#include "pico/time.h"
#include "pico/multicore.h"

#define LOG_TAG "MAIN"
#include "log/log.h"

static Bool is_server_work = True;
static Bool is_app_work    = True;

static void ServerCreate(void)
{
    TSrtInit();
    TMyMemoryCreate();
    TUartServerInit();
    TLogServerInit();
    TI2CServerInit();
}

static void ServerRun(void)
{
    UInt32 loop_ = 0;

    while (is_server_work)
    {
        TUartServerRunOnce();
        // if (loop_ % 100 == 0)
        // {
        //     for (Int32 idx = 0; idx < 5; idx ++)
        //         LOG_I("abc%d %d", idx, TGetTicks());
        // }

        loop_ ++;
        sleep_ms(10);
    }
}

static void ServerDestroy(void)
{
    TI2CServerFini();
    TLogServerFini();
    TUartServerFini();
    TMyMemoryDestroy();
    TSrtFini();
}


static void AppCreate(void)
{
    TCtrlInit();
    TScreenInit();
    TAdInit();
}

static void AppRun(void)
{
    UInt32 loop_ = 0;
    UInt32 cur_tick = 0;

    while (is_app_work)
    {
        cur_tick = TGetTicks();

        TCtrlRunOnce(cur_tick);
        TScreenRunOnce(cur_tick);
        TAdRunOnce(cur_tick);


        loop_ ++;
        sleep_ms(10);
    }
}

static void AppDestroy(void)
{
    TAdFini();
    TScreenFini();
    TCtrlFini();
}

static void AppEntry(void)
{
    AppCreate();

    AppRun();

    AppDestroy();
}

int main()
{
    ServerCreate();

    multicore_launch_core1(AppEntry);

    ServerRun();

    ServerDestroy();

    return 0;
}
